<template>
  <div>
    <a-modal title="辅料详情" :visible="visible" @before-open="open" @cancel="visible = false" :footer="false" :align-center="false" title-align="start" width="1000px" :mask-closable="false">
      <a-row>
        <a-col :span="24" style="display: flex">
          <div style="color: #a2a2a2; text-align: right; width: 70px">包装名称：</div>
          <div style="flex: 1">{{ info.skuName ? info.skuName : '' }}</div>
        </a-col>

        <a-col :span="8" class="mb10 mt10" style="display: flex">
          <div style="color: #a2a2a2; text-align: right; width: 70px">SKU：</div>
          <div style="flex: 1">{{ info.sku ? info.sku : '' }}</div>
        </a-col>
        <a-col :span="8" class="mb10 mt10" style="display: flex">
          <div style="color: #a2a2a2; text-align: right; width: 70px">长宽高：</div>
          <div style="flex: 1">{{ $extract(info, 'volume.length') }}×{{ $extract(info, 'volume.width') }}×{{ $extract(info, 'volume.height') }}（cm）</div>
        </a-col>
        <a-col :span="8" class="mb10 mt10" style="display: flex">
          <div style="color: #a2a2a2; text-align: right; width: 70px">重量：</div>
          <div style="flex: 1">{{ $extract(info, 'weight.weight') }}g</div>
        </a-col>
        <a-col :span="24" class="mb10 mt10" style="display: flex">
          <div style="color: #a2a2a2; text-align: right; width: 70px">关联店铺：</div>
          <div style="flex: 1">{{ getShop() }}</div>
        </a-col>
      </a-row>

      <div class="title-bar" style="margin: 10px 0">基本信息</div>

      <a-space class="mt10 mb10" v-if="productPicList[0]">
        <a-button class="gray-outline" @click="download">下载</a-button>
        <a-checkbox v-model="checkedAll" @change="selAll">全选</a-checkbox>
      </a-space>

      <a-row>
        <ul class="img-con clearfix fl" v-if="productPicList[0]">
          <li v-for="(item, index) of productPicList" :data-index="index" class="fl">
            <div class="master-map" v-if="index == 0"> 主图 </div>

            <div class="check-box">
              <a-checkbox v-model="item.checked"></a-checkbox>
            </div>

            <div class="mask">
              <div class="btn-con">
                <icon-eye class="cursor" style="margin-right: 15px" @click="showImgPre(index)" />
              </div>
            </div>
            <a-image :src="item.url" width="100%" height="100%" />
          </li>
          <a-image-preview-group v-model:visible="imgVisible" v-model:current="current" infinite :srcList="productPicList.map((e:any) => e.url)" />
        </ul>
        <a-empty v-else description="无图片信息" />
      </a-row>
    </a-modal>
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, computed, reactive } from 'vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import _, { values } from 'lodash-es'
  import { packDetail } from '@/api/product'
  import { toRefs } from 'vue'
  import JSZip from 'jszip'
  import FileSaver from 'file-saver'

  export default defineComponent({
    emits: ['save'],
    props: ['info'],
    setup(props, { emit }) {
      let visible = ref(false)
      const data: any = reactive({
        productPicList: [],
        current: 1,
        info: {},
        imgVisible: false,
      })
      const open = () => {
        getDetail()
      }

      const getDetail = async () => {
        const res: any = await packDetail(props.info.id)
        data.info = res?.data || {}
        data.productPicList = data.info?.productPicList || []
      }

      const getSrc = (data: any) => {
        return data?.productPicList[0]?.url || ''
      }

      const showImgPre = (index: number) => {
        data.current = index
        data.imgVisible = true
      }

      const getShop = () => {
        let shopList = props.info.shopList || []
        return shopList.map((e: any) => e.name).join('，')
      }

      const selAll = (val: boolean) => {
        data.productPicList.map((e: any) => {
          e.checked = val
          return e
        })
      }

      const download = () => {
        let list = data.productPicList.filter((e: any) => e.checked)
        if (!list[0]) {
          return Message.error('请选择产品图')
        }
        downloadBtn(list, '产品图')
        data.productPicList.map((e: any) => (e.checked = false))
      }

      const downloadBtn = (fileList: any, blogTitle: string) => {
        var zip: any = new JSZip()
        var promises = []
        let cache = {}
        for (let item of fileList) {
          // item.feilePath为文件链接地址
          // item.fileName为文件名称
          if (item.url) {
            const promise = getImgArrayBuffer(item.url).then((fileData) => {
              // 下载文件, 并存成ArrayBuffer对象(blob)
              let fileName = item.url.split('/')[item.url.split('/').length - 1]
              zip.file(fileName, fileData, { binary: true }) // 逐个添加文件
              cache[item.fileName] = fileData
            })
            promises.push(promise)
          } else {
            // feilePath地址不存在时提示
            alert(`附件${item.fileName}地址错误，下载失败`)
          }
        }
        Promise.all(promises)
          .then(() => {
            zip.generateAsync({ type: 'blob' }).then((content: any) => {
              // 生成二进制流
              FileSaver.saveAs(content, blogTitle) // 利用file-saver保存文件  blogTitle:自定义文件名
            })
          })
          .catch((res) => {
            alert('文件压缩失败')
          })
      }

      const getImgArrayBuffer = (url: string) => {
        return new Promise((resolve, reject) => {
          //通过请求获取文件blob格式
          let xmlhttp = new XMLHttpRequest()
          xmlhttp.open('GET', url, true)
          xmlhttp.responseType = 'blob'
          xmlhttp.onload = function () {
            if (xmlhttp.status == 200) {
              resolve(xmlhttp.response)
            } else {
              reject(xmlhttp.response)
            }
          }
          xmlhttp.send()
        })
      }

      return {
        ...(toRefs(data) as any),
        visible,
        open,
        getSrc,
        getShop,
        showImgPre,
        selAll,
        download,
      }
    },
  })
</script>

<style lang="less" scoped>
  .img-con {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    li {
      width: 160px;
      height: 160px;
      margin-right: 10px;
      margin-bottom: 5px;
      position: relative;

      .check-box {
        position: absolute;
        top: 5px;
        right: 5px;
        z-index: 2;
      }

      .master-map {
        position: absolute;
        left: 0;
        top: 0;
        background-color: #2da641;
        text-align: center;
        height: 20px;
        width: 40px;
        z-index: 5;
        font-size: 12px;
        line-height: 20px;
        color: white;
      }

      &:hover .mask {
        display: block;
      }
      .mask {
        display: none;
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 1;
        background: rgba(0, 0, 0, 0.5);

        .btn-con {
          width: 160px;
          color: white;
          font-size: 18px;
          text-align: center;
          margin-top: 76px;
          align-items: center;
        }
      }
    }
  }
</style>
